package org.dawfinn.droiditarian.listener;

import org.dawfinn.droiditarian.R;
import org.dawfinn.droiditarian.data.Deed;
import org.dawfinn.droiditarian.data.DeedsDBAdapter;
import org.dawfinn.droiditarian.deedfavoriteupload.DeedFavoriteUpload;
import org.dawfinn.droiditarian.deedfavoriteupload.InternetDeedFavoriteUpload;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class FavoriteStatusListener implements OnClickListener, OnMenuItemClickListener {

	private static final String FAVORITE_UPLOAD_PATH = "http://droiditarian.appspot.com/" + "favorite";
	private final Deed deed;
	private final DeedsDBAdapter db;
	private final Context context;

	/*
	 * The Handler and Runnable allow us to update the UI (make a toast) after
	 * completing something in a background thread.
	 */
	private Handler handler = new Handler();
	private Runnable doUploadFavorite = new Runnable() {

		public void run() {
			DeedFavoriteUpload uploader = new InternetDeedFavoriteUpload(FAVORITE_UPLOAD_PATH);
			uploader.sendDeedFavorite(deed, deed.isFavorite());
			Toast.makeText(context, R.string.favorite_status_updated, Toast.LENGTH_SHORT).show();
		}
	};

	public FavoriteStatusListener(Deed deed, Context context) {
		this.deed = deed;
		this.context = context;
		this.db = new DeedsDBAdapter(context);
	}

	public void onClick(View arg0) {
		doFavorite();
	}

	public boolean onMenuItemClick(MenuItem arg0) {
		doFavorite();
		return true;
	}

	private void doFavorite() {
		boolean isNowFavorite = !deed.isFavorite();
		deed.setFavorite(isNowFavorite);
		db.open();
		db.updateDeed(deed);
		db.close();
		new FavoriteAsyncTask().execute();
		deed.notifyOnDeedChangeListener();
	}

	class FavoriteAsyncTask extends AsyncTask<Boolean, Boolean, Boolean> {

		@Override
		protected Boolean doInBackground(Boolean... arg0) {
			handler.post(doUploadFavorite);
			return true;
		}

	}
}
